package logic

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"store/model/mysql"
	"store/model/redis"
	"store/storerpc/internal/svc"
	"store/storerpc/storerpc"
	"time"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *storerpc.ListRequest) (*storerpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	var lists []mysql.Product
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	get := redis.Client.Get("productlist" + in.Product)

	if get.Val() == "" {
		mysql.DB.Debug().Limit(int(in.Size)).Offset(int(offset)).Where("product like  ?", "%"+in.Product+"%").Model(&lists).Find(&lists)
		marshal, _ := json.Marshal(&lists)
		redis.Client.Set("productlist"+in.Product, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &lists)
	}

	var listStruct []*storerpc.ListStruct
	for _, list := range lists {
		Struct := &storerpc.ListStruct{
			Product:     list.Product,
			Price:       list.Price,
			Store:       list.Store,
			Description: list.Description,
			UserID:      int64(list.UserID),
		}
		listStruct = append(listStruct, Struct)
	}

	return &storerpc.ListResponse{List: listStruct}, nil
}
